class Barrage(object):

    def __init__(self, roomid):
        self.last = {}
        self.roomid = roomid
        self.barragels = []

    def play_new(self,max_ts = 1):
        assert max_ts >= 0, '最大延时不能小于0'
        from time import sleep
        while True:
            # newls = self.upgrade()
            # for new in newls:
            #     print(new)
            #     sleep(1)
            self.upgrade()
            bgls_len = len(self.barragels)
            # if self.barragels:
            #     1 ** 2 / (len(self.barragels) + 1)
            #     print(self.barragels.pop(0),len(self.barragels))
            while self.barragels:
                print(self.barragels.pop(0))
            if max_ts > 1:
                ts = (1/max_ts)**(bgls_len-1)
            else:
                ts = max_ts**2/(bgls_len+max_ts)
            # print(ts)
            sleep(ts)
            # sleep(ts-len(newls) if ts >= len(newls) else 0)


    def upgrade(self):
        new = self._getmsg()
        last_keys = self.last.keys()
        # new_barrage = []
        for rnd in new.keys():
            if rnd not in last_keys:
                # new_barrage.append(new[rnd])
                self.barragels.append(new[rnd])
        self.last = new.copy()
        # return new_barrage


    def _getmsg(self):
        from requests import post
        from jsonpath import jsonpath
        from json import loads
        api_url = r'https://api.live.bilibili.com/ajax/msg'
        post_data = {'roomid': self.roomid, }
        res = post(url=api_url, data=post_data)
        jsdata = loads(res.text)
        # textls = jsonpath(jsdata, '$.data.room..text')
        # rndls = jsonpath(jsdata, '$.data.room..rnd')
        textls = jsonpath(jsdata, '$.data..text')
        rndls = jsonpath(jsdata, '$.data..ct')
        jdata = zip(rndls, textls)
        return dict(jdata)

    